import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:taonile/config/config.dart';
import 'package:taonile/utils/local_file_utils.dart';
import 'package:taonile/views/search_appbar.dart';

import '../routers/routers.dart';
import '../utils/string_utils.dart';

///
/// 搜索页面
///
class SearchIndexPage extends StatefulWidget {
  var source = '0';

  SearchIndexPage({Key? key, this.source = ''}) : super(key: key);

  @override
  State<SearchIndexPage> createState() => _SearchIndexPageState();
}

class _SearchIndexPageState extends State<SearchIndexPage> {
  var _keyword = '';
  bool isDelete = false;

  List<String> history = [
    // '哇哈哈',
    // '电脑桌',
    // '狗绳',
    // '苹果电脑',
    // '华为',
    // '狗零食',
    // '蓝牙音箱',
    // '哇哈哈',
  ];
  List<String> hots = [
    '飞天茅台',
    '新风空调',
    '中式电视背景墙',
    '电脑',
    'iPhone 14 pro',
    '洽谈桌',
    'PS5',
    '75寸电视',
    '宠物零食',
  ];

  @override
  void initState() {
    super.initState();

    getProducts();
    getHistory();
  }

  getHistory() async {
    String result = await LocalFileUtils.readContent(LocalFileUtils.searchHistory);
    if (result.isNotEmpty) {
      var jsonResult = jsonDecode(result);
      List<String> obj = List.from(jsonResult);
      setState(() {
        history = obj;
      });
    }
  }

  saveHistory() async {
    await LocalFileUtils.writeContent(LocalFileUtils.searchHistory, jsonEncode(history));
  }

  getProducts() async {
    var param = {};
    // if (widget.keyword.isNotEmpty) {
    //   param['keyword'] = widget.keyword;
    // }
    // dynamic result = await Api.goodsList(param);
    // ProductEntity entity = ProductEntity.fromJson(result);
    // setState(() {
    //   if (page == 1) {
    //     datas.clear();
    //   }
    //   if (entity.data.isNotEmpty) {
    //     page++;
    //     datas.addAll(entity.data);
    //   }
    // });
  }

  getSearchHistory(int index) {
    return InkWell(
      onTap: () {
        if (isDelete) {
          //删除当前词条
          setState(() {
            history.removeAt(index);
            saveHistory();
          });
        } else {
          //去搜索当前词条
          Routes.navigateTo(context, Routes.productList, params: {'keyword': history[index]});
        }
      },
      child: Container(
        width: StringUtils.getStringWidth(history[index], 19.sp) + 30,
        height: 42.w,
        decoration: BoxDecoration(
          color: Config.colorWhite,
          borderRadius: BorderRadius.circular(20.w),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              history[index],
              style: TextStyle(color: Config.colorText1, fontSize: 19.sp),
            ),
            Visibility(
              visible: isDelete,
              child: Icon(
                Icons.close_rounded,
                color: Config.colorText2,
                size: 21.w,
              ),
            ),
          ],
        ),
      ),
    );
  }

  getSearchGuess(int index) {
    return InkWell(
      onTap: () {
        Routes.navigateTo(context, Routes.productList, params: {'keyword': hots[index]});
      },
      child: Container(
        width: StringUtils.getStringWidth(hots[index], 19.sp) + 30,
        height: 42.w,
        decoration: BoxDecoration(
          color: Config.colorWhite,
          borderRadius: BorderRadius.circular(20.w),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              hots[index],
              style: TextStyle(color: Config.colorText1, fontSize: 19.sp),
            ),
            Icon(
              Icons.local_fire_department,
              color: Colors.red,
              size: 21.w,
            )
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Config.colorBg2,
      appBar: AppBar(
        title: SearchAppBar(
          hintLabel: '请输入商品名称',
          callBack: (str) async {
            FocusManager.instance.primaryFocus?.unfocus();
            _keyword = str;
            if (_keyword.isEmpty) {
              return;
            }
            Routes.navigateTo(context, Routes.productList, params: {'keyword': _keyword});
            setState(() {
              history.add(str);
              saveHistory();
            });
          },
        ),
        centerTitle: true,
      ),
      body: Container(
          height: double.infinity,
          padding: EdgeInsets.symmetric(vertical: 25.w, horizontal: 25.w),
          width: double.infinity,
          // margin: EdgeInsets.only(top: 80.w),
          child: Column(
            children: [
              //历史搜索布局
              Visibility(
                visible: history.isNotEmpty,
                child: Container(
                  margin: EdgeInsets.only(bottom: 33.w),
                  child: Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            '搜索历史',
                            style: TextStyle(color: Config.colorText1, fontSize: 28.w),
                          ),
                          InkWell(
                            onTap: () {
                              setState(() {
                                isDelete = !isDelete;
                              });
                            },
                            child: !isDelete
                                ? Icon(
                                    Icons.delete_forever,
                                    size: 38.w,
                                  )
                                : Text(
                                    '完成',
                                    style: TextStyle(color: Config.colorMain, fontSize: 19.sp),
                                  ),
                          ),
                        ],
                      ),
                      Container(
                        margin: EdgeInsets.only(top: 20.w),
                        width: double.infinity,
                        child: Wrap(
                          spacing: 18.w,
                          runSpacing: 18.w,
                          children:
                              List.generate(history.length, (index) => getSearchHistory(index)),
                        ),
                      ),
                    ],
                  ),
                ),
              ),

              //猜你想搜
              Container(
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          '猜你想搜',
                          style: TextStyle(color: Config.colorText1, fontSize: 28.w),
                        ),
                        Icon(
                          Icons.refresh,
                          size: 38.w,
                        )
                      ],
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 20.w),
                      width: double.infinity,
                      child: Wrap(
                        spacing: 18.w,
                        runSpacing: 18.w,
                        children: List.generate(hots.length, (index) => getSearchGuess(index)),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          )),
    );
  }
}
